/**
  * Author: Mei
  * Date: 2020-12-05 10:50
  * Description: 信号量的使用
  *
  */
#include <semaphore.h>
#include <thread>
#include <functional>
#include <iostream>

using namespace std;

typedef function<void()> callback;
class Foo {
protected:
    sem_t first_sem;
    sem_t second_sem;
public:
    Foo() {
        sem_init(&first_sem, 0, 0);
        sem_init(&second_sem, 0, 0);
    }

    void first(callback printFirst) {
        printFirst();
        sem_post(&first_sem);
    }

    void second(callback printSecond) {
        sem_wait(&first_sem);
        printSecond();
        sem_post(&second_sem);
    }

    void third(callback printThird) {
        sem_wait(&second_sem);
        printThird();
    }
};

void printFirst() {
    cout << "first" << endl;
}

void printSecond() {
    cout << "second" << endl;
}

void printThird() {
    cout << "third" << endl;
}

int main() {
    Foo f;
    thread t3{&Foo::third, &f, printThird};
    thread t2{&Foo::second, &f, printSecond};
    thread t1{&Foo::first, &f, printFirst};

    t1.join();
    t2.join();
    t3.join();

    return 0;
}